package cn.xiuxius.embedded.comdev;

import org.jline.reader.LineReader;
import org.jline.reader.UserInterruptException;
import org.jline.reader.EndOfFileException;
import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStyle;

public class ComTerminal {

    private final LineReader reader;
    private final AttributedString prompt = new AttributedString("> ",
            AttributedStyle.DEFAULT.foreground(AttributedStyle.WHITE));

    private final MessageDispatcher dispatcher;

    public ComTerminal(LineReader reader, MessageDispatcher dispatcher) {
        this.reader = reader;
        this.dispatcher = dispatcher;
    }

    public boolean run() {
        try {
            String line = reader.readLine(prompt.toAnsi());
            if ("exit".equalsIgnoreCase(line.trim())) {
                return false;
            }
            if ("hex -s".equalsIgnoreCase(line.trim())) {
                dispatcher.setSendHex(!dispatcher.isSendHex());
                dispatcher.dispatchSystemMessage("Send hex mode: " + dispatcher.isSendHex());
                return true;
            }

            if ("hex -r".equalsIgnoreCase(line.trim())) {
                dispatcher.setReceiveHex(!dispatcher.isReceiveHex());
                dispatcher.dispatchSystemMessage("Receive hex mode: " + dispatcher.isReceiveHex());
                return true;
            }
            dispatcher.dispatchSentMessage(line);
        } catch (UserInterruptException e) {
            // Ctrl+C 退出
            return false;
        } catch (EndOfFileException e) {
            // Ctrl+D 退出
            return false;
        }
        return true;
    }

}
